from src.database.connection import Neo4jInstance


def add_property():
    storey_order()  # 楼层先后关系建立
    # 分部、分项、分层、分段
    add_pi_work_property()


# 楼层先后关系建立
def storey_order():
    graph = Neo4jInstance.get_connect()
    # 查找 IfcBuilding 构件
    building = graph.evaluate("MATCH (b:IfcBuilding) RETURN b")

    if building:
        building_id = building["GlobalId"]
        # print(f"Found IfcBuilding with GlobalId: {building_id}")

        # 查找 IfcBuilding 包含的所有 IfcBuildingStorey
        storeys = graph.run(
            """
            MATCH (b:IfcBuilding {GlobalId: $building_id})-[:CONTAINS]->(s:IfcBuildingStorey)
            RETURN s
        """,
            building_id=building_id,
        ).data()

        if storeys:
            # 按照 Elevation 对楼层进行排序
            sorted_storeys = sorted(storeys, key=lambda x: x["s"]["Elevation"])

            # 建立先后顺序，最低 楼层IfcBuildingStorey 的前置是 整体建筑IfcBuilding
            pre_dependence_id = None
            # 将排序后的信息保存回 Neo4j 数据库
            for index, storey in enumerate(sorted_storeys):
                current_id = storey["s"]["GlobalId"]
                # 给楼层加上个 SortIndex 属性
                graph.run(
                    """
                    MATCH (s:IfcBuildingStorey {GlobalId: $current_id})
                    SET s.SortIndex = $index
                """,
                    current_id=current_id,
                    index=index,
                )

                # 创建楼层之间的 dependence 关系
                if pre_dependence_id is not None:
                    graph.run(
                        """
                        MATCH (low_storey {GlobalId: $pre_dependence_id}),(high_storey {GlobalId: $current_id})
                        MERGE (high_storey)-[:FOLLOW]->(low_storey)
                    """,
                        pre_dependence_id=pre_dependence_id,
                        current_id=current_id,
                    )
                pre_dependence_id = current_id

            # # 建筑与首层建立关系
            # graph.run(
            #     """
            # MATCH (parent {GlobalId: $parent_id}),(child {GlobalId: $child_id})
            # MERGE (child)-[:DEPENDENCE]->(parent)
            # """,
            #     parent_id=building_id,
            #     child_id=sorted_storeys[0]["s"]["GlobalId"],
            # )


# TODO 后面改……
# 分部
def add_pi_work_property():
    graph = Neo4jInstance.get_connect()
    # work_section 分部
    types = [
        "IfcBuilding",
        "IfcBuildingStorey",
        "IfcColumn",
        "IfcBeam",
        "IfcSlab",
        "IfcWall",
        "IfcWallStandardCase",
        "IfcDoor",
    ]
    query = f" MATCH (n) WHERE n.type in {types} SET n.WorkSection = '土建工程' "
    graph.run(query)

    # work_item 分项
    types = [
        "IfcBuilding",
        "IfcBuildingStorey",
    ]
    query = f" MATCH (n) WHERE n.type in {types} SET n.WorkItem = '基础工程' "
    graph.run(query)

    types = [
        "IfcColumn",
        "IfcBeam",
        "IfcSlab",
    ]
    query = f" MATCH (n) WHERE n.type in {types} SET n.WorkItem = '主体结构工程' "
    graph.run(query)

    # work_storey 分层
    types = [
        "IfcColumn",
        "IfcBeam",
        "IfcSlab",
        "IfcWall",
        "IfcWallStandardCase",
        "IfcDoor",
    ]
    query = f"""MATCH (c)-[:PLACED_IN]->(s:IfcBuildingStorey) 
        WHERE c.type in {types}
        SET c.layer = s.Name
    """
    graph.run(query)
